package com.zhentao.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.entity.UserVip;
import com.zhentao.entity.VipPackage;
import com.zhentao.mapper.UserVipMapper;
import com.zhentao.mapper.VipPackageMapper;
import com.zhentao.service.VipService;
import com.zhentao.vo.UserVipInfoVO;
import com.zhentao.vo.VipPackageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * VIP服务实现类
 */
@Service
public class VipServiceImpl implements VipService {
    
    @Autowired
    private VipPackageMapper vipPackageMapper;
    
    @Autowired
    private UserVipMapper userVipMapper;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public UserVipInfoVO getVipInfo(Long userId) {
        UserVipInfoVO vo = new UserVipInfoVO();
        
        // 查询用户当前生效的VIP
        UserVip currentVip = userVipMapper.selectActiveVipByUserId(userId);
        
        if (currentVip != null && currentVip.getEndTime().isAfter(LocalDateTime.now())) {
            vo.setIsVip(true);
            vo.setVipExpireTime(currentVip.getEndTime());
            
            // 计算剩余天数
            long days = ChronoUnit.DAYS.between(LocalDateTime.now(), currentVip.getEndTime());
            vo.setRemainingDays((int) days);
        } else {
            vo.setIsVip(false);
            vo.setVipExpireTime(null);
            vo.setRemainingDays(0);
        }
        
        // 查询所有VIP套餐
        List<VipPackage> packages = vipPackageMapper.selectAllActive();
        List<VipPackageVO> packageVOs = new ArrayList<>();
        
        for (VipPackage pkg : packages) {
            VipPackageVO pkgVO = new VipPackageVO();
            pkgVO.setPackageId(pkg.getPackageId());
            pkgVO.setName(pkg.getPackageName());
            pkgVO.setDurationDays(pkg.getDurationDays());
            pkgVO.setDuration(getDurationText(pkg.getDurationDays()));
            pkgVO.setOriginalPrice(pkg.getOriginalPrice());
            pkgVO.setPrice(pkg.getCurrentPrice());
            pkgVO.setRecommend(pkg.getIsRecommend() == 1);
            
            // 解析特权列表JSON
            try {
                if (pkg.getBenefits() != null && !pkg.getBenefits().isEmpty()) {
                    List<String> benefits = objectMapper.readValue(
                        pkg.getBenefits(), 
                        new TypeReference<List<String>>() {}
                    );
                    pkgVO.setBenefits(benefits);
                } else {
                    pkgVO.setBenefits(new ArrayList<>());
                }
            } catch (Exception e) {
                // JSON解析失败时记录日志并使用空列表
                System.err.println("解析套餐 " + pkg.getPackageId() + " 的 benefits 失败: " + e.getMessage());
                System.err.println("原始数据: " + pkg.getBenefits());
                pkgVO.setBenefits(new ArrayList<>());
            }
            
            packageVOs.add(pkgVO);
        }
        
        vo.setPackages(packageVOs);
        
        return vo;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean purchaseVip(Long userId, Long packageId) {
        // 查询套餐信息
        VipPackage pkg = vipPackageMapper.selectById(packageId);
        if (pkg == null || pkg.getStatus() != 1) {
            throw new RuntimeException("套餐不存在或已下架");
        }
        
        // 生成订单号
        String orderNo = generateOrderNo();
        
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now;
        LocalDateTime endTime;
        
        // 查询用户当前VIP状态
        UserVip currentVip = userVipMapper.selectActiveVipByUserId(userId);
        if (currentVip != null && currentVip.getEndTime().isAfter(now)) {
            // 如果已有VIP，从当前VIP结束时间开始累加
            startTime = currentVip.getEndTime();
        }
        
        // 计算结束时间
        endTime = startTime.plusDays(pkg.getDurationDays());
        
        // 创建VIP记录
        UserVip userVip = new UserVip();
        userVip.setUserId(userId);
        userVip.setPackageId(packageId);
        userVip.setStartTime(startTime);
        userVip.setEndTime(endTime);
        userVip.setDurationDays(pkg.getDurationDays());
        userVip.setPaymentAmount(pkg.getCurrentPrice());
        userVip.setPaymentMethod("在线支付"); // TODO: 实际支付方式
        userVip.setOrderNo(orderNo);
        userVip.setStatus(1);
        userVip.setSource("购买");
        userVip.setCreateTime(now);
        
        int result = userVipMapper.insert(userVip);
        
        return result > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean grantVip(Long userId, Integer days, String source) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now;
        LocalDateTime endTime;
        
        // 查询用户当前VIP状态
        UserVip currentVip = userVipMapper.selectActiveVipByUserId(userId);
        if (currentVip != null && currentVip.getEndTime().isAfter(now)) {
            // 如果已有VIP，从当前VIP结束时间开始累加
            startTime = currentVip.getEndTime();
        }
        
        // 计算结束时间
        endTime = startTime.plusDays(days);
        
        // 创建VIP记录
        UserVip userVip = new UserVip();
        userVip.setUserId(userId);
        userVip.setPackageId(0L); // 赠送的VIP没有套餐ID
        userVip.setStartTime(startTime);
        userVip.setEndTime(endTime);
        userVip.setDurationDays(days);
        userVip.setPaymentAmount(BigDecimal.ZERO);
        userVip.setPaymentMethod("赠送");
        userVip.setOrderNo(generateOrderNo());
        userVip.setStatus(1);
        userVip.setSource(source);
        userVip.setCreateTime(now);
        
        int result = userVipMapper.insert(userVip);
        
        return result > 0;
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "VIP" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
    }
    
    /**
     * 获取时长单位文字
     */
    private String getDurationText(Integer days) {
        if (days == 30) return "月";
        if (days == 90) return "季";
        if (days == 365) return "年";
        return days + "天";
    }
}


